package com.jwater.core.utils;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import jwater.org.apache.commons.io.IOUtils;
import jwater.org.dom4j.Document;
import jwater.org.dom4j.DocumentHelper;
import jwater.org.springframework.core.io.Resource;
import jwater.org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import jwater.org.springframework.core.io.support.ResourcePatternResolver;

/**
 * @description:
 * @author: jnner
 * @createDate: 2021/2/5
 * @version: 1.0
 */
public class LoggerUtils {
    /**
     * 初始化日志
     *
     * @param is
     */
    public static void loadConfigFile(InputStream is) {
        LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
        try {
            JoranConfigurator configurator = new JoranConfigurator();
            configurator.setContext(lc);
            lc.reset();
            String xmlFile = null;
            if (is == null) {
                ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
                Resource resources[] = resolver.getResources("classpath*:logback/logback.xml");
                xmlFile = IOUtils.toString(resources[0].getInputStream(), "UTF-8");
            } else {
                xmlFile = IOUtils.toString(is, "UTF-8");
            }
            Document xmlDoc = DocumentHelper.parseText(xmlFile);
            configurator.doConfigure(new ByteArrayInputStream(xmlDoc.asXML().getBytes()));
            // StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
